package com.randb.easyhttp.body;

import com.randb.easyhttp.utils.HttpLog;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Sink;

/**
 * User: RandBII
 * Date: 2020/5/29
 * Description:
 */
public class UploadProgressRequestBody extends RequestBody {

    protected RequestBody delegate;
    protected ProgressResponseCallback callback;

    public UploadProgressRequestBody(ProgressResponseCallback callback) {
        this.callback = callback;
    }

    public UploadProgressRequestBody(RequestBody delegate, ProgressResponseCallback callback) {
        this.delegate = delegate;
        this.callback = callback;
    }

    public void setRequestBody(RequestBody body) {
        this.delegate = body;
    }


    @Nullable
    @Override
    public MediaType contentType() {
        return delegate.contentType();
    }

    @Override
    public void writeTo(@NotNull BufferedSink bufferedSink) throws IOException {


    }


    protected class CountingSink extends ForwardingSink {

        private long bytesWritten = 0;
        private long contentLength = 0;
        private long lastRefreshTime;

        public CountingSink(@NotNull Sink delegate) {
            super(delegate);
        }

        @Override
        public void write(@NotNull Buffer source, long byteCount) throws IOException {
            super.write(source, byteCount);
            if (contentLength <= 0) contentLength = contentLength();
            bytesWritten += byteCount;
            long currentTime = System.currentTimeMillis();

            if (System.currentTimeMillis() - currentTime > 300 || bytesWritten == contentLength) {
                callback.onResponseProgress(bytesWritten, contentLength, bytesWritten == contentLength);
                lastRefreshTime = System.currentTimeMillis();
            }
            HttpLog.i("bytesWritten =" + bytesWritten + ",totalBytesCount =" + contentLength);
        }
    }
}
